<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2019-01-03 20:14:16
 * @Description: 角色管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-30 18:20:58
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Rbac/RoleController.php
 */

namespace App\Http\Controllers\Console\Rbac;

use App\Models\Rbac\Menu;
use App\Models\Rbac\Role;
use App\Models\Rbac\Admin;
use Illuminate\Http\Request;
use App\Models\Rbac\RoleAdmin;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\BatchRequest;
use App\Models\Rbac\RolePermission;
use App\Exceptions\FireFlyException;
use App\Http\Controllers\Controller;
use App\Http\Requests\DetailRequest;
use App\Http\Requests\StatusRequest;
use App\Http\Requests\Ums\RoleRequest;
use App\Http\Requests\Ums\RolePrivRequest;
use App\Http\Requests\Ums\RoleAdminRequest;
use App\Http\Requests\Ums\RoleUpdateRequest;

class RoleController extends Controller
{
    public function getList(Request $request)
    {
        $key = $request->input('key','');
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $query = Role::where(function ($q) use ($key) {
            if ($key != '') {
                $q->where('name', 'like', '%' . $key . '%');
            }
        });
        $count = $query->count();
        $list = $query->limit($size)->offset(($page - 1) * $size)->orderBy('id','asc')->get();
        return $this->resJson(200,'成功', ['list' => $list, 'count' => $count]);
    }
    public function postCreate(RoleRequest $request)
    {
        $name = $request->input('name');
        $status = $request->input('status');
        Role::create(['name'=>$name,'status'=>$status]);
        return $this->resJson(200,'成功');
    }
    public function getDetail(DetailRequest $request)
    {
        $detail = Role::findOrFail($request->input('detail_id'));
        return $this->resJson(200, '成功', $detail);
    }
    public function postEdit(RoleUpdateRequest $request)
    {
    
        $name = $request->input('name');
        $status = $request->input('status');
        Role::where('id',$request->input('detail_id'))->update(['name'=>$name,'status'=> $status]);
        return $this->resJson(200,'成功');
    }
    public function postStatus(StatusRequest $request)
    {
        $status = $request->input('status');
        Role::where('id',$request->input('detail_id'))->update(['status'=>$status]);
        return $this->resJson(200,'成功');
    }
    public function postRemove(BatchRequest $request)
    {
        $detail_id = $request->input('detail_id',[]);
        if (in_array(1, $detail_id)) {
            throw new FireFlyException(403,'超级管理员组不能删除');
        }
        // 查询下属用户
        if(RoleAdmin::where('role_id',$detail_id)->count() > 0)
        {
            throw new FireFlyException(403,'角色下有用户，请先确认所有用户身份已更改完成');
        }
        // 同时删除关联的用户关系
        DB::transaction(function() use($detail_id){
            Role::whereIn('id',$detail_id)->delete();
            RolePermission::whereIn('role_id',$detail_id)->delete();
        });
        return $this->resJson(200,'成功');
    }
    public function getPriv(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        // 所有权限
        $priv = RolePermission::where('role_id', $detail_id)->select('id','menu_id')->get();
        // 所有菜单
        $all = Menu::select('id','parent_id','name','url')->orderBy('sort','asc')->orderBy('id','asc')->get();
        // 变成树形菜单用的
        $tree = $this->toTree($priv,$all,0);
        return $this->resJson(200,'成功',$tree);
    }
    private function toTree($priv,$data,$pid)
    {
        $tree = [];
        if ($data->count() > 0) {
            foreach($data as $v)
            {
                if ($v->parent_id == $pid) {
                    $v = ['menu_id'=>$v->id,'title'=>$v->name,'expand'=>false];
                    // 所有子菜单都选中的时候，此菜单选中checked，部分选中时selected
                    $child_count = $data->where('parent_id',$v['menu_id'])->count();
                    // 没有子菜单的时候，判断他本身
                    if ($child_count == 0) {
                        $v['checked'] = $priv->where('menu_id',$v['menu_id'])->count() > 0 ? true : false;
                    }
                    $v['children'] = $this->toTree($priv,$data,$v['menu_id']);
                    $tree[] = $v;
                }
            }
        }
        return $tree;
    }
    public function postPriv(RolePrivRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $ids = $request->input('menu_id',[]);
        DB::transaction(function() use($detail_id,$ids){
            RolePermission::where('role_id',$detail_id)->delete();
            // 所有选中的菜单url，以此查找出所有url label
            $all = Menu::whereIn('id',$ids)->get();
            // 将查出来的数据组成数组插入到role_privs表里
            if (!is_null($all) && count($all) > 0) {
                foreach ($all as $v) {
                    $insertArr[] = ['role_id' => $detail_id, 'menu_id' => $v->id, 'name' => $v->name, 'url' => $v->url, 'label' => $v->label, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                }
                RolePermission::insert($insertArr);
            }
        });
        return $this->resJson(200,'成功');
    }
    public function postAdminList(DetailRequest $request)
    {
        $admin_ids = RoleAdmin::where('role_id',$request->input('detail_id'))->pluck('admin_id');
        $list = Admin::whereIn('id',$admin_ids)->orderBy('id', 'asc')->get();
        return $this->resJson(200, '获取数据成功', $list);
    }
    public function postRemoveAdmin(RoleAdminRequest $request)
    {
        RoleAdmin::where('role_id', $request->input('detail_id'))->where('admin_id', $request->input('admin_id'))->delete();
        return $this->resJson(200, '成功');
    }
}
